﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using eShop.Model;

namespace eShop.Business
{
    public class ShoppingCartManager
    {
        private const string SHOPPING_CART = "Shopping_Cart";
        private static Cart ShoppingCart
        {
            get
            {
                if (System.Web.HttpContext.Current.Session[SHOPPING_CART] != null)
                    return (Cart)System.Web.HttpContext.Current.Session[SHOPPING_CART];

                return new Cart();
            }
            set { System.Web.HttpContext.Current.Session[SHOPPING_CART] = value; }
        }

        public static void AddProductToCart(int productId, int stockId, int quantity)
        {
            Product product = ProductManager.GetProductById(productId);
            ProductStock stock = ProductStockManager.GetStockById(stockId);
            if (quantity > 0)
            {
                Cart shoppingcart = ShoppingCart;
                CartItem cartItem = new CartItem(product, stock, quantity, product.ProductPrice);
                shoppingcart.AddCartItem(cartItem);
                ShoppingCart = shoppingcart;
            }
        }

        public static void RemoveProductFromCart(int productId, int stockId)
        {
            Cart cart = ShoppingCart;
            cart.CartItems.RemoveAll(item => item.Product.ProductId == productId);
            ShoppingCart = cart;
        }

        public static void UpdateProductInCart(int productId, int stockId, int quantity)
        {
            Cart cart = ShoppingCart;
            cart.UpdateCartItem(productId, quantity);
            ShoppingCart = cart;
        }

        public static CartItem FindItem(int productId)
        {
            return ShoppingCart.CartItems.Find(item => item.Product.ProductId == productId);
        }

        public static bool HasAnyItemInCart()
        {
            if (ShoppingCart == null || ShoppingCart.CartItems.Count <= 0)
                return false;
            return true;
        }

        public static Cart GetCart()
        {
            return ShoppingCart;
        }

        public static List<CartItem> GetCartItems()
        {
            return ShoppingCart.CartItems;
        }

        public static void ClearCart()
        {
            ShoppingCart = null;
        }
    }
}
